package com.example.xx.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
// 启用安全框架
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class Myconfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private Jwtconfig jwtconfig;
    @Autowired
    private QuanXianBuZuconfig quanXianBuZuconfig;
    @Autowired
    private NoLoginconfig noLoginconfig;
    public PasswordEncoder cc() {
        return new BCryptPasswordEncoder();
    }


    /**
     * 设置我们controller请求需要的东西
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // spring security也要处理跨域问题
        http.cors(Customizer.withDefaults());// springsecurity结合springmvc 一起处理跨域问题
        http.csrf().disable();// 关闭跨站请求伪造  否则每次登录除了需要携带用户名和密码 还需要携带一个随机数
        // 任何人不需要登录就可以访问/hello  安全框架不会对/hello这个请求做认证 也不会做鉴权
        http.authorizeRequests().antMatchers("/user/denglu").permitAll();
        // http.authorizeRequests() 前端发来的任何请求 除/user/login之外的任何一个请求必须经过认证(登录)
        http.authorizeRequests().anyRequest().authenticated();// 除此之外的其他请求必须登录
        http.exceptionHandling().accessDeniedHandler(quanXianBuZuconfig);// 权限不足处理时候的处理，使用自定义的类去进行处理
        http.exceptionHandling().authenticationEntryPoint(noLoginconfig);// 没有登录处理时候的处理，使用自定义的类去进行处理

        http.addFilterBefore(jwtconfig, UsernamePasswordAuthenticationFilter.class);// 添加我们自定义的过滤器 放在登录过滤器之前


    }
}
